<script setup lang="ts">
import { usePrintStore } from '@/stores'
import type { FormInstance, FormRules } from 'element-plus'
import { DY_MAP_VisibleScales } from '@/constants'

const printtingStore = usePrintStore()
const emit = defineEmits(['update:modelValue'])
const scaleInfoForm = reactive<ScaleInfo>({
  scaleText: '',
  style: 'BAR',
  segments: '',
  unit: 'METER'
})
const scaleInfoFormRef = ref<FormInstance>()
const rules = reactive<FormRules<ScaleInfo>>({
  style: [{ required: true, message: '请选择样式', trigger: 'blur' }],
  unit: [{ required: true, message: '请选择单位', trigger: 'blur' }]
})

function toOtherForm(type: any) {
  emit('update:modelValue', type)
}

async function submitScaleInfoForm(formEl: FormInstance | undefined, type: string) {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (!valid) return
    printtingStore.submitScaleInfoForm(scaleInfoForm)
    emit('update:modelValue', type)
    const zoom = map.getZoom()
    const { lng, lat } = map.getCenter()
    printtingStore.mapScale = DY_MAP_VisibleScales[Math.round(zoom)].toString()
    printtingStore.mapCenter = `${lng},${lat}`
  })
}

watch(
  () => printtingStore.scaleInfo,
  (newVal) => Object.assign(scaleInfoForm, newVal)
)
</script>

<template>
  <div>
    <el-form ref="scaleInfoFormRef" :rules="rules" :model="scaleInfoForm" label-position="right">
      <el-form-item label="比例尺文本：" label-width="100px">
        <el-input v-model="scaleInfoForm.scaleText" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="样式：" prop="style" label-width="100px">
        <el-select v-model="scaleInfoForm.style" placeholder="bar" style="width: 300px">
          <el-option label="line" value="LINE" />
          <el-option label="bar" value="BAR" />
          <el-option label="bar_sub" value="BAR_SUB" />
        </el-select>
      </el-form-item>
      <el-form-item label="段数：" label-width="100px">
        <el-input v-model="scaleInfoForm.segments" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="单位：" prop="unit" label-width="100px">
        <el-select v-model="scaleInfoForm.unit" placeholder="单位选择" style="width: 300px">
          <el-option label="米" value="METER" />
          <el-option label="英里" value="FOOT" />
          <el-option label="度" value="DEGREES" />
        </el-select>
      </el-form-item>
    </el-form>
    <div class="btn-group">
      <el-button type="warning" @click="toOtherForm('additionInfo')" style="margin-right: 50px">上一步</el-button>
      <el-button type="primary" @click="submitScaleInfoForm(scaleInfoFormRef, 'outOptions')">下一步</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.btn-group {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
